package com.yycwxt.modules.front.test.controller;

import com.yycwxt.modules.front.test.result.Result;
import com.yycwxt.modules.front.test.util.ExcelUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

@RestController
public class ExcelToDatabase {
    @PostMapping("/exceltest")
    public Result excelToDatebase(MultipartFile file){
        // 原始文件名
        String fileName = file.getOriginalFilename();
        // 文件后缀
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        // 返回数据封装到Result
        Result result = new Result();

        try (InputStream inputStream = file.getInputStream()){
            if(".xlsx".equals(fileSuffix) || ".xls".equals(fileSuffix)){
                // Excel解析完返回list
                List list = ExcelUtil.readExcel(inputStream, file.getOriginalFilename());
                for (Object o:list){
                    System.out.println(o.toString());
                }
                result.setCode("200");
                result.setMsg("上传成功");
                result.setData(null);
            }
            else{
                // 不是Excel文件
                result.setCode("201");
                result.setMsg("不支持的文件类型");
                result.setData(null);
            }
        }
        catch (Exception e){
            // 抛出异常
            result.setCode("500");
            result.setMsg("服务器出错");
            result.setData(null);
        }


        return result;
    }

//    @PostMapping("/excel2")
//    public Result excelToDatabase2(MultipartFile file){
//
//    }
}
